<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { HttpStatusCode } from 'axios'
import { addBanner } from '../../../../api/banner'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import config from "../../../../config"

let formLabelAlign = reactive<Banner>({
  banner_name: '',
  banner_url: '',
})
const imageUrl = ref('')
const emits = defineEmits(['increase', 'closeShow'])
const submitData = async () => {
  const res = await addBanner(formLabelAlign)
  if(res.statusCode === HttpStatusCode.Created) {
    ElMessage({
      message: '添加成功',
      type: 'success',
    })
    emits('increase', 1, '')
    emits('closeShow')
  } else {
    ElMessage({
      message: '添加失败',
      type: 'error',
    })
  }
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  const { path } = response.data
  formLabelAlign.banner_url = path.replace(/\\/g, '/')
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('请上传JPG/PNG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片最大大小为10MB!')
    return false
  }
  return true
}
</script>

<template>
  <el-form
      label-position="top"
      label-width="100px"
      :model="formLabelAlign"
      style="max-width: 460px"
  >
    <el-form-item label="轮播图名称">
      <el-input v-model="formLabelAlign.banner_name" />
    </el-form-item>
    <el-form-item label="班级封面">
      <el-upload
          class="avatar-uploader"
          :action="config.uploadUrl + '/api/upload/image'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="submitData">提交</el-button>
</template>

<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  .avatar {
    width: 200px;
    height: 200px;
    object-fit: contain;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
